package com.onpositive.mediawiki.crawler;

import java.util.ArrayList;
import java.util.Collection;

import net.sourceforge.jwbf.core.actions.Get;
import net.sourceforge.jwbf.core.actions.util.HttpAction;
import net.sourceforge.jwbf.mediawiki.actions.queries.TitleQuery;
import net.sourceforge.jwbf.mediawiki.actions.util.VersionException;
import net.sourceforge.jwbf.mediawiki.bots.MediaWikiBot;

public class IdForTitleQuery extends TitleQuery<String>
{

	protected String title;

	protected IdForTitleQuery(MediaWikiBot bot, String title) throws VersionException
	{		
		super(bot);
		this.title = title;
	}

	@Override
	protected HttpAction prepareCollection()
	{
		String uS = "/api.php?action=query&titles=" + title.replaceAll(" ","_") + "&format=xml";
		return new Get(uS);
	}

	@Override
	protected Collection<String> parseArticleTitles(String s)
	{
		ArrayList<String> result = new ArrayList<String>();
		int idx = s.indexOf("pageid");		
		if (idx >= 0)
		{
			try
			{
				int valStartIdx = s.indexOf('"',idx);
				int valEndIdx = s.indexOf('"',valStartIdx + 1);
				String txtVal = s.substring(valStartIdx+1,valEndIdx).trim();
				if (Integer.parseInt(txtVal) >= 0) //Really, for checking that we've got valid integer
				{
					result.add(txtVal);
					return result;
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	protected String parseHasMore(String s)
	{
		// TODO Auto-generated method stub
		return null;
	}

}
